import { useLoad } from '@tarojs/taro';
import { View, Image, Textarea } from '@tarojs/components';
import { useRef, useState, useCallback, useEffect } from 'react';
import cssModule from './index.module.scss';
import Taro from '@tarojs/taro';

/**
 * @description 搜索
 * @author Shawn
 */

// 组件接收的参数
interface NavigationBarProps {
  value?: string; // 输入框的值
  placeholder?: string; // 输入框的占位符
  type?: 'text' | 'number' | 'idcard' | 'digit'; // 输入框的类型
  isDisabled?: boolean; // 输入框是否禁用
  onChange?: (value: string) => void; // 输入变化回调
}

export default function SearchBox({
  value,
  placeholder = '请输入搜索内容',
  isDisabled = false,
  onChange,
}: NavigationBarProps) {
  const [inputValue, setInputValue] = useState(value || '');
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 获取系统信息
  const systemInfo = Taro.getSystemInfoSync();
  const isAndroid = systemInfo.platform === 'android';

  useLoad(() => {
    console.log('Page loaded.');
  });

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, []);

  // 同步外部 value 的变化
  useEffect(() => {
    if (value !== undefined) {
      setInputValue(value);
    }
  }, [value]);

  const handleInput = useCallback((e: any) => {
    const newValue = e.detail.value;
    setInputValue(newValue);

    // 清除之前的定时器
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    // 设置新的定时器，延迟 500ms 后调用 onChange
    timerRef.current = setTimeout(() => {
      onChange?.(newValue);
    }, 500);
  }, [onChange]);

  return (
    <View className={cssModule.container}>
      <View className={cssModule.searchBox}>
        <Image src='https://baoyouqun.cn/files/static/images/search.png' mode='aspectFill' />
        <Textarea
          className={`${cssModule.searchText} ${!isAndroid ? 'h-[66px]' : 'h-[33px]'}`}
          maxlength={15}
          showConfirmBar={true}
          disabled={isDisabled}
          focus
          showCount
          confirmType='done'
          placeholder={placeholder}
          value={inputValue}
          onInput={handleInput}
        />
      </View>
    </View>
  );
}
